<template>
	<view class="relative full-screen">
		<view style="z-index:0;position:absolute;left:0;right:0;top:0;height:396px;background-image:radial-gradient(circle at left top, #D8230A26 50%, transparent 50%);background-size:396px 396px;background-repeat:no-repeat;filter:blur(50px);"></view>
		<uni-nav-bar ref="navBar" fixed statusBar :border="false" backgroundColor="transparent" @clickLeft="goBack">
			<template v-slot:left>
				<image class="size-32" src="@/static/svg/icon-back.svg"  v-if="!redirect" />
			</template>
		</uni-nav-bar>
		<view class="flex-col item-center" :style="`height: calc(100vh - ${navBarHeight || 0}px);`">
			<image style="width:88px;height:88px;margin-top:52px;" src="@/static/image/login-logo.png" />
			<text class="mt-20 text-center text-color-regular fs-20 font-semibold">欢迎来到火动通告</text>
			<view class="w-full flex-1 h-0" style="max-height:190px;"></view>
			<view class="mx-16 black text-center fs-14 font-normal">
				<button class="h-46 leading-46 radius-23 bg-primary text-white fs-16 font-semibold" :open-type="isAgreementCheck && !token ? 'getPhoneNumber' : ''"
					@getphonenumber="getPhoneNumber" @click="quickLoginHandle">一键登录</button>
				<button class="my-20 mx-0 h-38 leading-38 radius-20 uni-border text-color-hint fs-14 font-normal" @click="loginHandle">手机号登录</button>
				<view class="flex align-center" @click="agreementCheckHandle">
					<label for="agreement">
						<image v-if="isAgreementCheck" class="size-13" src="@/static/svg/radio-checked.svg"></image>
						<image v-else class="size-13" src="@/static/svg/radio-default.svg"></image>
						我已阅读并同意<text class="color-primary" @click.stop="toLink('user')">《用户服务协议》</text>和<text class="color-primary" @click.stop="toLink('privacy')">《隐私协议》</text>
					</label>
				</view>
			</view>
		</view>

		<NickNameAndAvatarPopup ref="popup" @onSubmit="onSubmit" />
	</view>
</template>

<script setup name="Login">
	import {
		computed,
		onMounted,
		ref,
		getCurrentInstance,
		watch
	} from 'vue'
	import {
		authCodeApi,
		getWxMobileApi
	} from '@/api/auth.js'
	import {
		uploadFileApi
	} from '@/api/common.js'
	import NickNameAndAvatarPopup from './components/NickNameAndAvatarPopup.vue'
	import {onLoad} from '@dcloudio/uni-app'
	import {
		useUserStore
	} from '@/stores/modules/user.js'
	import { useWebView } from '@/hooks/useWebView.js'
	
	const webview = useWebView()
	let redirect = ref(null)
	let code = ref(null)
	const from = ref('') // 从哪个页面触发登录的
	const userStore = useUserStore()
	const instance = getCurrentInstance()

	const navBar = ref(null)

	const goBack = () => {
		if(!redirect.value){
			// 仅有一个页面时，返回首页
			if(getCurrentPages().length === 1) {
				uni.reLaunch({
					url: '/pages/home/home'
				})
				return
			}
			uni.navigateBack()
		}
	}
	const linkUrl = () => {
		if(redirect.value == 'busi'){
			let params = code.value?`?code=${code.value}`:``
			uni.redirectTo({
				url: `/applyPages/bussinessApply/bussinessAgreement${params}`
			})
		}else if(redirect.value == 'bbus'){
			let params = code.value?`?code=${code.value}`:``
			uni.redirectTo({
				url: `/applyPages/bindBusiness/bindBusiness${params}`
			})
		} else if (from.value) {
			const eventChannel = instance.ctx.getOpenerEventChannel()
			eventChannel.emit('onLoginSuccess')
			uni.navigateBack()
		}else{
			uni.redirectTo({
				url: '/pages/home/home'
			})
		}
	}
	const isAgreementCheck = ref(false)

	const agreementCheckHandle = () => {
		isAgreementCheck.value = !isAgreementCheck.value
	}
	
	const toLink = (type) => {
		if (type === 'user') {
			webview.showUserAgreement('用户服务协议')
		} else if (type === 'privacy') {
			webview.showPrivacyPolicy('隐私协议')
		}
	}

	const popup = ref(null)

	const getPhoneNumber = async ({
		detail
	}) => {
		if (detail.errMsg === 'getPhoneNumber:ok') {
			const result = await getWxMobileApi({
				encryptedData: detail.encryptedData,
				iv: detail.iv,
				openId: openId.value
			})
			if (result) {
				popup.value.showPopup(true)
			}
		} else if (detail.errMsg) {
			uni.showToast({
				icon: 'none',
				title: '您取消了授权'
			})
		}
	}
	
	const loginHandle = () => {
		// 手机号登录~
		if (!isAgreementCheck.value) {
			uni.showToast({
				icon: 'none',
				title: '请先阅读并同意用户协议与隐私政策'
			})
		}else{
			let url = `/pagesA/login/phone-login?from=${encodeURIComponent(from.value)}`
			if(redirect.value){
				url += `&re=${encodeURIComponent(redirect.value)}`
			}
			if(code.value){
				url += `&code=${encodeURIComponent(code.value)}`
			}
			uni.navigateTo({
				url
			})
		}
	}

	const quickLoginHandle = async (e) => {
		if (!isAgreementCheck.value) {
			uni.showToast({
				icon: 'none',
				title: '请先阅读并同意用户协议与隐私政策'
			})
		} else if (token.value) {
			uni.showLoading()
			userStore.setToken(token.value)
			await userStore.getUserInfo()
			uni.hideLoading()
			linkUrl()
			
		}
	}

	// 不登录，返回上一页面
	const noLoginHandle = () => {
		// 仅有一个页面时，返回首页
		if(getCurrentPages().length === 1) {
			uni.reLaunch({
				url: '/pages/home/home'
			})
		} else {
			uni.navigateBack()
		}
	}

	const openId = ref('')
	const token = ref('')

	const getOpenId = async () => {
		const res = await uni.login({
			provider: 'weixin'
		})
		console.log('res code', res.code)
		if (res.code) {
			const result = await authCodeApi((res.code))
			if (result.token) {
				// 已注册
				token.value = result.token
				// userStore.setToken(token.value)
				// await userStore.getUserInfo()
				// linkUrl()
			} else {
				// 未注册
				openId.value = result.openId
			}
		}
	}

	const onSubmit = async (form) => {
		popup.value.showPopup(false)
		uni.showLoading()
		await userStore.login({
			openId: openId.value,
			...form
		})
		await userStore.getUserInfo()
		uni.hideLoading()
		linkUrl()
	}
	
	const navBarHeight = computed(() => {
		const statusBarHeight = uni.getWindowInfo().statusBarHeight
		const navigationBarHeight = statusBarHeight + (navBar.value && navBar.value.height || 0)
		return navigationBarHeight
	})

	onMounted(() => {
		getOpenId()
	})
	onLoad((query) => {
		console.log(query)
		from.value = query.from || ''
		if(query.re){
			redirect.value = query.re
			code.value = query.code
		}
	})
</script>
